package com.fishleap.controller;

import com.fishleap.util.CuratorUtils;
import com.fishleap.util.DruidUtils;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author zlg
 * @create 2020-06-30 7:41
 */
@Component
public class DatasourceConfig {

    // 在执行Spring beans初始化时，就会执行该函数
    // 该函数中执行的初始化操作应当不依赖于其他Spring beans
    @PostConstruct
    public void init() {

        // 初始化zookeeper和数据源
//        initZookeeperInfo();
        DruidUtils.ininDatasource();

        // 测试数据库连接
        UserController.list();

        // 测试修改数据库配置
        while (true) {
            for (int i = 0; i < 1000; i++) {
                if (i % 2 == 0) {
                    setData();
                }else {
                    setData2();
                }
            }
        }


    }

    /**
     * 在 zookeeper 上初始化配置信息: 命名空间 mysql-config 节点 database
     * eg: /mysql-config/dataBase
     */
    private void initZookeeperInfo() {
        String nodePath = "/database";
        String nodeData = "{\"url\":\"jdbc:mysql://localhost:3306/user?serverTimezone=UTC\",\"username\":\"root\",\"password\":\"root\"}";
        CuratorUtils.createPersistentNode(nodePath, nodeData);
    }

    private static void setData2() {

        String nodePath = "/database";
        String nodeData = "{\"url\":\"jdbc:mysql://localhost:3306/user2?serverTimezone=UTC\",\"username\":\"root\",\"password\":\"root\"}";
        CuratorUtils.setNodeData(nodePath, nodeData);

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//            Thread.sleep(Integer.MAX_VALUE);
    }
    private static void setData() {

        String nodePath = "/database";
        String nodeData = "{\"url\":\"jdbc:mysql://localhost:3306/user?serverTimezone=UTC\",\"username\":\"root\",\"password\":\"root\"}";
        CuratorUtils.setNodeData(nodePath, nodeData);

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
